package com.ld.security.auth.shiro.anno.aop;

import com.ld.security.auth.common.sys.entity.SysAjaxLogEntity;
import com.ld.security.auth.common.sys.mapping.SysAjaxLogMapping;
import com.ld.security.common.core.util.AopUtil;
import com.ld.security.common.core.util.JsonUtil;
import com.ld.security.common.core.util.UuidUtil;
import com.ld.security.common.mybatis.base.vo.DataVo;
import com.ld.security.common.tomcat.anno.AjaxLogKey;
import com.ld.security.common.tomcat.util.SessionUtil;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * 请求日志记录
 */
@Component
@Aspect
@Order(5)
public class SysLogAjaxAop {

    @Autowired
    SysAjaxLogMapping sysAjaxLogMapping;


    @Pointcut("@annotation(com.ld.security.common.tomcat.anno.AjaxLogKey)")
    public void aop() {

    }

   @Around("aop()")
    public Object doAroundAdvice(ProceedingJoinPoint pjp) throws Throwable{
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();

        Object val =  pjp.proceed();

        String label="";
       AjaxLogKey sysAjaxLogKey =  AnnotationUtils.findAnnotation(method, AjaxLogKey.class);

       ApiOperation apiOperation =  AnnotationUtils.findAnnotation(method, ApiOperation.class);
       if(apiOperation != null){
           label =  apiOperation.value();
       }

        SysAjaxLogEntity log = new SysAjaxLogEntity();

       log.setId(UuidUtil.getId());
       log.setClassName(pjp.getTarget().getClass().getSimpleName());
       log.setMethodName(method.getName());
       log.setIp(SessionUtil.getIPAddress());
       log.setLabel(label);
       log.setUrl(SessionUtil.getUrl());
       if(sysAjaxLogKey.inParams()){
           log.setInParams(JsonUtil.toJson(AopUtil.getParams(pjp)));
       }
       if(sysAjaxLogKey.outParams()){
           log.setOutParams(JsonUtil.toJson(val));
       }

       log.setCrtTime(new Date());
       log.setUptTime(new Date());



       if(val instanceof DataVo){
           DataVo dataVo = (DataVo)val;
           log.setCode(dataVo.getCode()+"");
       }else{
           log.setCode("200");
       }


       CompletableFuture.runAsync(() -> {
           sysAjaxLogMapping.insert(log);
       });





        return val;
    }



}
